import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QScrollArea, QLabel, QSizePolicy
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt, QEvent


class ImageViewer(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('惰性加载图片查看器')
        self.setGeometry(100, 100, 800, 600)

        # 创建一个垂直布局
        main_layout = QVBoxLayout()

        # 创建一个滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        main_layout.addWidget(scroll_area)

        # 创建一个内容容器
        self.scroll_content = QWidget()
        self.scroll_content.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        scroll_area.setWidget(self.scroll_content)

        # 创建一个垂直布局用于内容容器
        self.content_layout = QVBoxLayout(self.scroll_content)
        self.content_layout.setAlignment(Qt.AlignTop)

        # 图片列表
        self.image_paths = ['./resources/scaled.jpg' for i in range(1000)]  # 假设你有1000张图片

        # 加载的图片索引
        self.loaded_images = 0

        # 初始加载一些图片
        self.load_images(0, 100)

        # 安装事件过滤器以便处理滚动事件
        scroll_area.viewport().installEventFilter(self)

        self.setLayout(main_layout)

    def load_images(self, start, end):
        for i in range(start, end):
            if self.loaded_images >= len(self.image_paths):
                break
            image_path = self.image_paths[self.loaded_images]
            if os.path.exists(image_path):
                label = QLabel()
                pixmap = QPixmap(image_path)
                label.setPixmap(pixmap)
                self.content_layout.addWidget(label)
                self.loaded_images += 1

    def eventFilter(self, source, event):
        if event.type() == QEvent.Wheel:
            scroll_area = self.findChild(QScrollArea)
            if scroll_area is not None:
                # 获取垂直滚动条的位置和范围
                scrollbar = scroll_area.verticalScrollBar()
                position = scrollbar.value()
                max_position = scrollbar.maximum()

                # 当滚动条接近底部时加载更多图片
                if position > max_position - max_position / 4:
                    self.load_images(self.loaded_images, self.loaded_images + 100)
        return super().eventFilter(source, event)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    viewer = ImageViewer()
    viewer.show()
    sys.exit(app.exec_())
